package com.suneee.ep.proxy.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Http {
	private static Logger log =LoggerFactory.getLogger(Http.class);
	
	public static String doPostData(String url, TreeMap<String, String> params) {
		
		log.info("start http post,params {}",Utils.toJson(params));
		
		String resultString=null;
		
		DefaultHttpClient httpclient = new DefaultHttpClient();
		int defaultTimeout = 10000; 
		 
		int connectionlevel = 3000;
		HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),connectionlevel);
		 
		int solevel = 30000;
		HttpConnectionParams.setSoTimeout(httpclient.getParams(),solevel);	

		// 目标地址
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
		List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
		// 参数及值
		Iterator it = params.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String name = entry.getKey().toString();
			String value = entry.getValue().toString();
			if(name!=null&&name.length()>0){
				nvps.add(new BasicNameValuePair(name, value));
			}
		}
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

			// 执行
			HttpResponse response = httpclient.execute(httppost);
			
			System.out.println("StatusCode: " + response.getStatusLine().getStatusCode());
			System.out.println("ReasonPhrase: " + response.getStatusLine().getReasonPhrase());
			
			if(response.getStatusLine().getStatusCode()!=200){
				return "{\"is_success\":false,\"error_code\":\"" + response.getStatusLine().getStatusCode()
						+ "\",\"message\":\"调用接口失败\"}";
			}
			HttpEntity entity = response.getEntity();
			resultString=new String((EntityUtils.toString(entity)+"").getBytes("ISO-8859-1"),"UTF-8");
			
			log.info("http post return {}", resultString );
			
		} catch (Exception e) { 
			log.error("http post exception:", e);
		}
 
		return resultString;
	}
	
}
